import Taro from '@tarojs/taro'
import { Current } from '@tarojs/taro'
import React, { PureComponent, useEffect, useRef, useState } from 'react'
// 界面组件
import { View, Text, ScrollView, RadioGroup, Label, Radio, Image } from '@tarojs/components'
import { AtRadio, AtList, AtListItem, AtAccordion, AtTabs, AtTabsPane, AtTextarea, AtCheckbox } from 'taro-ui'
import CTopbar from '@/components/CTopbar/index'
import prefixZero from '@/utils/prefixZero.ts'
import { get_evaluation_info_api, submit_test_api } from './service'
import './index.scss'
import unique from '@/utils/unique'
import GetTopBarInfo from '@/utils/GetTopBarInfo' //动态高度
import CTestRadio from '@/components/CTestRadio'
import CTestInput from '@/components/CTestInput'
/**
 * 测试页
 * 
 * 答案格式
 *      const params = {
        options: [{ optionIds: [], questionId: 0 }],  测试题【测试题选项id数组，测试题id】
        questionInfo: [{ problem: '', answer: '' }],  填空题【问题 答案】
        questionNameId:0  测试卷id
      }
 */

//  返给后端的选择题类型
export interface options {
  optionIds: number[]
  questionId: number
  isScoring: number
}

// 返给后端的填空题类型
export interface questionInfo {
  problem: string
  answer: string
  isScoring: number
}
//  选项类型
export interface IOptions {
  id: number
  jumpQuestionId: string
  optionContext: string
  optionFraction: number
  optionImg: string
  questionOption: string
}

//  题的类型
export interface IQuestions {
  id: number
  options: IOptions[]
  question: string
  questionNameId: number
  questionSerial: number
  questionType: number
}

interface IData {
  isTest: number
  question: IQuestions[]
  questionImg: string
  questionName: string
  questionNumber: number
  questionSubtitle: string
  remarks: string
  settlementType: number
  id: number
}

function TestQuestions() {
  const { id } = Taro.useRouter().params
  const [params, setparams] = useState<(questionInfo | options)[]>([]) //重新组装的 做题数组
  const [questionData, setQuestionData] = useState<IQuestions[]>([]) //题目数组
  const [currentIndex, setcurrentIndex] = useState(0) //当前题的索引   0
  const [resData, setResData] = useState<IData | null>() //后台返回的对象数据
  const questionType = useRef(0) // 题型  1单选  2多选 3填空
  const isFrist = useRef(true) //是否是第一题   是就阻止渲染
  useEffect(() => {
    // 请求测试题
    const FetchData = () => {
      get_evaluation_info_api(Number(id)).then(({ result, data }) => {
        init(data.question)
        setQuestionData(data.question)
        setResData(data)
      })
    }
    FetchData()
  }, [])

  // 初始化数据
  function init(data) {
    if (data.length === 0) {
      return
    }
    let questionInput: (questionInfo | options)[] = []
    data.map((item) => {
      if (item.questionType === 3) {
        const a: questionInfo = {
          problem: item.question,
          answer: '',
          isScoring: item.isScoring,
        }
        questionInput.push(a)
      } else {
        const b: options = {
          optionIds: [],
          questionId: item.id,
          isScoring: item.isScoring,
        }
        // 初始化 题目的类型
        questionType.current = data[0].questionType
        questionInput.push(b)
      }
    })
    setparams(questionInput)
  }
  // 上一题
  function preTest() {
    setcurrentIndex(currentIndex - 1)
  }

  // 下一题
  function nextTest() {
    console.log(params)

    if (params[currentIndex].answer === '') {
      Taro.showToast({
        title: '请填写答案',
        icon: 'none',
        mask: true,
      })
    } else {
      isFrist.current = false
    }
    if (params[currentIndex].optionIds && params[currentIndex].optionIds.length === 0) {
      Taro.showToast({
        title: '请选择答案',
        icon: 'none',
        mask: true,
      })
      return
    }

    // 跳转题型
    const optionsItem = questionData[currentIndex].options.find((item) => item.id === params[currentIndex].optionIds[0])
    let str = /^[A-Za-z]{1}$/ //一位字母
    let regStr = /^\d{1,2}$/ //一位或者两位数字
    // 如果是跳转题
    if (resData?.settlementType === 2) {
      if (optionsItem) {
        console.log(optionsItem.jumpQuestionId)

        //如果存在选项
        if (optionsItem && str.test(optionsItem.jumpQuestionId)) {
          // 如果jumpQuestionId 带字母
          submitTest()
        } else if (regStr.test(optionsItem.jumpQuestionId)) {
          // 如果jumpQuestionId 带数字
          setcurrentIndex(parseInt(optionsItem.jumpQuestionId) - 1)
        } else {
        }
      } else {
        //如果不存在选项  直接下一题
        setcurrentIndex(currentIndex + 1)
      }
    } else {
      //如果不是跳转题 直接下一题
      setcurrentIndex(currentIndex + 1)
    }
  }

  // 提交
  function submitTest() {
    Taro.showLoading({
      title: '加载中',
      mask: true,
    })
    if (params[currentIndex].answer === '') {
      Taro.showToast({
        title: '请填写答案',
        icon: 'none',
        mask: true,
      })
    } else {
      isFrist.current = false
    }
    if (params[currentIndex].optionIds && params[currentIndex].optionIds.length === 0) {
      Taro.showToast({
        title: '请选择答案',
        icon: 'none',
        mask: true,
      })
      return
    }
    let obj = { questionInfo: [], options: [], questionNameId: -1 }
    params.map((item, index) => {
      if (item.answer) {
        obj.questionInfo.push(item)
      } else {
        obj.options.push(item)
      }
    })
    obj.questionNameId = Number(id)
    // 提交答案
    Taro.setStorage({ key: 'TestResults', data: obj })
    setTimeout(() => {
      Taro.hideLoading()
      Taro.redirectTo({
        url: '/pages/Home/HomeEvaluationResults/index?id=' + id,
      })
    }, 300)
  }

  // 单选多选的 change事件
  function submitChange(v) {
    let a = [...params]
    a[currentIndex] = v
    isFrist.current = false
    setparams(a)
  }

  // 根据params是否渲染  单选或者多选才渲染
  useEffect(() => {
    if (isFrist.current === true || questionType.current === 3 || questionType.current === 2) return
    // if (currentIndex === 0) {
    //   //这里初次加载 不能延迟500ms  否则再加上初始化数据所需时间就会发生页面空白时间太长
    //   nextTest()
    // } else {
    setTimeout(() => {
      if (currentIndex === questionData.length - 1) return
      nextTest()
    }, 500)
    // }
  }, [params])

  // 根据currentIndex  是否渲染 questionData有值就更改全局的题目的类型
  useEffect(() => {
    if (questionData.length > currentIndex) {
      questionType.current = questionData[currentIndex].questionType
    }
  }, [currentIndex])
  console.log(questionData[currentIndex])

  return (
    <View style={{ paddingTop: `${GetTopBarInfo().TopBarHeight}px` }}>
      <View className='header'>
        <CTopbar title='心理测评' showBack></CTopbar>
      </View>
      <View className='content'>
        {/* 单选和多选 */}
        {questionData.length > 0 && questionData.length > currentIndex && questionData[currentIndex].questionType !== 3 && (
          <CTestRadio
            index={currentIndex + 1}
            data={questionData[currentIndex]}
            selectedData={params[currentIndex]}
            submitChange={(v) => submitChange(v)}
          />
        )}

        {/* 填空题 */}
        {questionData.length > 0 && questionData.length > currentIndex && questionData[currentIndex].questionType === 3 && (
          <CTestInput
            index={currentIndex + 1}
            data={questionData[currentIndex]}
            value={params[currentIndex].answer}
            handleChange={(v) => {
              let a = [...params]
              a[currentIndex].answer = v
              setparams(a)
            }}
          />
        )}

        <View className='btn-box'>
          {currentIndex !== 0 && <View onClick={preTest}>上一题</View>}
          {questionData.length > currentIndex + 1 && <View onClick={nextTest}>下一题</View>}
          {questionData.length - 1 === currentIndex && <View onClick={submitTest}>提交</View>}
        </View>
      </View>
    </View>
  )
}

export default TestQuestions
